package com.pz.gulimall.product.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pz.gulimall.common.exception.BizCodeEnum;
import com.pz.gulimall.common.exception.RRException;
import com.pz.gulimall.common.to.ShopCarItemTo;
import com.pz.gulimall.common.utils.PageUtils;
import com.pz.gulimall.common.utils.Query;
import com.pz.gulimall.common.utils.R;
import com.pz.gulimall.product.dao.ShopCarDao;
import com.pz.gulimall.product.entity.ShopcarItemEntity;
import com.pz.gulimall.product.service.ShopCarService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service("shopCarService")
public class ShopCarServiceImpl extends ServiceImpl<ShopCarDao, ShopcarItemEntity> implements ShopCarService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ShopcarItemEntity> page = this.page(
                new Query<ShopcarItemEntity>().getPage(params),
                new QueryWrapper<ShopcarItemEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R queryByLoginId(String loginId) {
        if(loginId != null && !StringUtils.isEmpty(loginId)){
            List<ShopcarItemEntity> items = this.list(new QueryWrapper<ShopcarItemEntity>().eq("login_id", loginId));
            return R.ok().put("data", items);
        } else {
            throw new RRException(BizCodeEnum.PRODUCT_LOGIN_ID_EMPTY.getMsg(), BizCodeEnum.PRODUCT_LOGIN_ID_EMPTY.getCode());
        }
    }

    /**
     *
     * @param shopcarItems 来自redis的缓存数据
     */
    @Override
    @Transactional
    public void saveItems(List<ShopCarItemTo> shopcarItems) {
        List<ShopcarItemEntity> shopcarItemEntities = new ArrayList<>();
        shopcarItems.forEach(item -> {
            ShopcarItemEntity shopcarItemEntity = new ShopcarItemEntity();
            BeanUtils.copyProperties(item, shopcarItemEntity);
            shopcarItemEntities.add(shopcarItemEntity);
        });
        if(!shopcarItemEntities.isEmpty()){
            List<ShopcarItemEntity> collect1;
            try {
                //1. 更新操作 UPDATE `pms_shopcar_item` set ... where login_id = loginId && sku_id = skuId
                this.baseMapper.updateByLoginIdAndSkuId(shopcarItemEntities);
                //2.1 从数据库搜索出 login_id = loginId && sku_id = skuId 搜集为collect1，
                collect1 = this.baseMapper.queryBathByLoginIdAndSkuId(shopcarItemEntities);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RRException(BizCodeEnum.MYSQL_EXCEPTION.getMsg(), BizCodeEnum.MYSQL_EXCEPTION.getCode());
            }

            Set<String> loginIdSkuIdSet = new HashSet<>();
            // 将已经存在的数据项的 loginId+skuId 集合为 set
            collect1.forEach(c -> {
                loginIdSkuIdSet.add(c.getLoginId()+c.getSkuId());
            });

            //2.2 然后将 shopcarItemEntities 中 没有存在在数据库中的数据条过滤出来为collect2，作为新数据插入
            List<ShopcarItemEntity> collect2 = shopcarItemEntities.stream().filter(item -> !loginIdSkuIdSet.contains(item.getLoginId() + item.getSkuId())).collect(Collectors.toList());

            //3.将 collect2 的数据插入到数据库
            boolean b;
            try {
                b = this.saveBatch(collect2);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RRException(BizCodeEnum.MYSQL_EXCEPTION.getMsg(), BizCodeEnum.MYSQL_EXCEPTION.getCode());
            }
        }
    }

    @Override
    public R queryBatchByLoginIds(List<String> loginIds) {
        try {
            List<ShopcarItemEntity> shopcarItemEntities = this.baseMapper.queryByLoginIds(loginIds);
            return R.ok().put("data", shopcarItemEntities);
        } catch (Exception e) {
            throw new RRException(BizCodeEnum.MYSQL_EXCEPTION.getMsg(), BizCodeEnum.MYSQL_EXCEPTION.getCode());
        }

    }

    @Override
    public R delItems(String loginId, List<Long> skuIds) {
        boolean b;
        try {
            b = this.baseMapper.deleteByLoginIdAndSkuIds(loginId, skuIds);
        } catch (Exception e) {
            throw new RRException(BizCodeEnum.MYSQL_EXCEPTION.getMsg(), BizCodeEnum.MYSQL_EXCEPTION.getCode());
        }
        if(b){
            return R.ok("有数据项被删除");
        }else {
            return R.ok("没有数据项被删除");
        }
    }


}
